viewable-one 0.12.9 → 0.12.11

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 CHANGED
@@ -13,6 +13,37 @@ package.
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [0.12.11] - 2026-11-25
17
+
18
+ ### Fixed
19
+
20
+ - A computer no longer stops taking asks when the server's firewall refuses
21
+ one of a run's saved log lines or its result (#8648). A log line that quoted
22
+ code such as `require('fs').writeFileSync(` got Cloudflare's 403 page, and
23
+ the runner kept it to send forever while it claimed nothing. Now the calls
24
+ that carry a run's own text (`events`, `update`, `resume`, `opResult`) go
25
+ base64-encoded, which `board-runner` unwraps; an older function that answers
26
+ `Unknown op ""` gets the plain body once and is remembered. When the
27
+ function itself is reachable (it answered, or a tiny call to the same op in
28
+ the same flush got its JSON back) and still will not take a saved line, the
29
+ line moves to `run-completions/<folder>/set-aside/` and a skipped-line
30
+ marker takes its place at the same seq. A refused result is kept there too,
31
+ and a short note ends the run instead. A whole-computer block, the network,
32
+ a 5xx or a 429 are retried as before and never set anything aside. Each set
33
+ aside writes one `runner.log` line with the run id, seq and Ray ID.
34
+
35
+ ## [0.12.10] - 2026-11-25
36
+
37
+ ### Fixed
38
+
39
+ - An ask on Your computer that only reads no longer runs the folder's tests
40
+ and build after its answer (#8611). It changed nothing, so the run ends when
41
+ the session ends instead of up to 5 minutes later, and its result no longer
42
+ says "Ran out of time". The same goes for an ask that worked in the folder
43
+ itself (no copy) and changed nothing there: a git folder is compared with
44
+ how it was when the ask started. An ask that changed files, in its copy or
45
+ in the folder, is checked as before.
46
+
16
47
  ## [0.12.9] - 2026-11-25
17
48
 
18
49
  ### Added
package/SPAWN.md CHANGED
@@ -145,6 +145,16 @@ The runner retries exact receipts after restart and blocks new admission while
145
145
  any receipt remains undelivered. A failed disk write retains the patch in memory
146
146
  and attempts delivery; simultaneous disk/network failure cannot survive process
147
147
  loss. The server accepts identical retries and rejects conflicting results.
148
+ A receipt the server will never take does not block for good (#8648): when
149
+ the function itself is reachable (it answered, or a tiny call to the same op
150
+ in the same flush got its JSON back) and refuses the body, or its own refusal
151
+ repeats for 5 flushes, the receipt moves to `run-completions/<folder>/set-aside/`
152
+ and a stand-in takes its name: a `cut` marker at the same seq for a log line,
153
+ a note in place of the result for a terminal patch (then only status, finish
154
+ time and the note). Network failures, 5xx, 429 and a 403 from a closed
155
+ address never count. The calls that carry a run's text (`events`, `update`,
156
+ `resume`, `opResult`) go base64-encoded, so a firewall in front of the
157
+ function never reads code in them.
148
158
 
149
159
  **How often the runner calls the board (ticket e8, approved 2026-10-03; #616).**
150
160
  `lib/runnerPace.mjs` decides every wait for both loops of a folder:
@@ -619,6 +629,8 @@ the same `newOpId` shape the ops channel uses).
619
629
  `Write`, `Edit`, `Bash` or web tools), Codex in its read-only sandbox with
620
630
  its board server kept and no web search. Neither loads the computer's own
621
631
  apps (`computerApps` is ignored). A value that is not a boolean is refused.
632
+ It runs no package checks after it ends (#8611); nor does any run in the
633
+ folder itself (no worktree) that left a git folder as it found it.
622
634
 
623
635
  ### `<id>.claim` - who owns it
624
636
 
@@ -0,0 +1,43 @@
1
+ // Whether a run in the folder itself changed anything (#8611): a run with no
2
+ // copy has no base to diff against, so the runner keeps the folder's state
3
+ // from the start and compares it at the end (runnerLaunch.mjs).
4
+ import { createHash } from "node:crypto";
5
+ import { lstat } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { git } from "./worktree.mjs";
8
+
9
+ // Past this many untracked files the state is not worth reading; the run is
10
+ // checked as before.
11
+ const MAX_UNTRACKED = 5000;
12
+
13
+ /** One hash of what a run in a git folder can change: the commit it is on,
14
+ * every tracked change against it (staged or not), and the untracked files
15
+ * by size and time. Equal hashes before and after a run mean it changed
16
+ * nothing (#8611). Ignored files do not count, the way they do not for a
17
+ * copy's changed files. null when the folder is not a git checkout or git
18
+ * could not answer, which means "may have changed". Reads only: no index
19
+ * refresh (`--no-optional-locks`), so the person's own git is never blocked. */
20
+ export async function folderState(cwd) {
21
+ const run = (args, at = cwd) => git(["--no-optional-locks", "-c", "core.quotePath=false", ...args], at);
22
+ const top = await run(["rev-parse", "--show-toplevel"]);
23
+ if (!top.ok) return null;
24
+ const root = top.stdout.trim();
25
+ const hash = createHash("sha256");
26
+ const head = await run(["rev-parse", "--verify", "-q", "HEAD"], root);
27
+ hash.update(`head ${head.ok ? head.stdout.trim() : "none"}\0`);
28
+ // No commit yet: the staged and unstaged changes, each against what is before it.
29
+ for (const args of head.ok ? [["diff", "--binary", "--no-ext-diff", "HEAD"]] : [["diff", "--binary", "--no-ext-diff"], ["diff", "--binary", "--no-ext-diff", "--cached"]]) {
30
+ const diff = await run(args, root);
31
+ if (!diff.ok) return null;
32
+ hash.update(`${args.join(" ")}\0${diff.stdout}\0`);
33
+ }
34
+ const untracked = await run(["ls-files", "-z", "--others", "--exclude-standard"], root);
35
+ if (!untracked.ok) return null;
36
+ const paths = untracked.stdout.split("\0").filter(Boolean).sort();
37
+ if (paths.length > MAX_UNTRACKED) return null;
38
+ for (const path of paths) {
39
+ const info = await lstat(join(root, path)).catch(() => null);
40
+ hash.update(`${path}\0${info ? `${info.size}:${info.mtimeMs}` : "gone"}\0`);
41
+ }
42
+ return hash.digest("hex");
43
+ }
package/lib/runnerApi.mjs CHANGED
@@ -101,18 +101,35 @@ export function cloudflareRayId(headers, text) {
101
101
 
102
102
  const looksLikeHtml = (text) => typeof text === "string" && /^\s*<(?:!doctype|html)/i.test(text);
103
103
 
104
+ /** The ops whose body carries a run's own text: a log line, a result, a
105
+ * late message, an op's outcome. A firewall in front of the function can
106
+ * read code in that text as an attack and answer 403 (#8648), so these go
107
+ * as `{enc: "b64", data}`, which board-runner unwraps before anything else.
108
+ * The rest carry only ids and stay plain. */
109
+ export const ENCODED_OPS = new Set(["events", "update", "resume", "opResult"]);
110
+
111
+ /** Addresses whose function predates the encoding: it answered an encoded
112
+ * body `Unknown op ""`. Kept for this process, so each call there costs one
113
+ * request, not two. */
114
+ const plainOnly = new Set();
115
+
116
+ const encode = (body) => ({ enc: "b64", data: Buffer.from(JSON.stringify(body), "utf8").toString("base64") });
117
+ const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
118
+
104
119
  /** One call to the board-runner function. Never throws on a network or HTTP
105
120
  * failure - every caller gets `{ok:false, error}` back and decides for
106
121
  * itself whether that is worth logging, retrying on the next poll, or
107
122
  * surfacing on a receipt. `op` and the rest of `body` are sent flat, per the
108
- * contract's `{op, ...}` shape. */
123
+ * contract's `{op, ...}` shape (encoded for ENCODED_OPS). */
109
124
  async function call(op, body = {}, options = {}) {
110
125
  const { env = process.env } = options;
111
126
  const { appUrl } = await hostedConfig({ env });
112
127
  const url = runnerApiUrlFrom(appUrl, env);
128
+ const plain = { op, ...body };
129
+ const encoded = ENCODED_OPS.has(op) && !plainOnly.has(url);
113
130
  let result;
114
131
  try {
115
- result = await authenticatedJsonPost(url, { op, ...body }, options);
132
+ result = await authenticatedJsonPost(url, encoded ? encode(plain) : plain, options);
116
133
  } catch (error) {
117
134
  // "fetch failed" alone says nothing; undici puts the reason (ENOTFOUND,
118
135
  // ECONNRESET, a TLS code) on `cause` (QA 2026-10-01, e8).
@@ -125,6 +142,17 @@ async function call(op, body = {}, options = {}) {
125
142
  if (result.authError) return { ok: false, unauthorized: true, error: result.authError };
126
143
 
127
144
  const { response, text, payload } = result;
145
+ // AN OLDER FUNCTION (#8648): it reads no `enc`, finds no op and says so.
146
+ // Send the same call plain, and remember the address, before this answer
147
+ // is read as a refusal. `realtime` is never encoded, so an older
148
+ // function still answers it `Unknown op "realtime"` (runnerRealtime.mjs).
149
+ if (encoded && response.status === 400 && typeof payload?.error === "string" && payload.error.startsWith('Unknown op ""')) {
150
+ plainOnly.add(url);
151
+ return call(op, body, options);
152
+ }
153
+ // Answered by the function itself: its own `{ok, ...}` envelope, not a
154
+ // page or a gateway's JSON in front of it (a 404 for a missing function).
155
+ const fromFunction = isObject(payload) && typeof payload.ok === "boolean" ? { fromFunction: true } : {};
128
156
  if (!response.ok) {
129
157
  // A CLOUDFLARE PAGE (#616): a rate limit answers 429 with a whole HTML
130
158
  // page, not JSON. Four hundred characters of markup told nobody
@@ -139,11 +167,19 @@ async function call(op, body = {}, options = {}) {
139
167
  // function's own logs, where board-runner now writes the cause.
140
168
  const requestId = response.headers?.get?.("sb-request-id");
141
169
  const transient = response.status >= 500 || response.status === 429;
170
+ // `permanent` (#8648): a 4xx that sending the same body again will not
171
+ // change. Settlement still asks whether the function itself is reachable
172
+ // before it treats this as a refusal of the content (a firewall can block
173
+ // a whole computer with the same 403).
174
+ const permanent = response.status >= 400 && response.status < 500 && ![401, 408, 429].includes(response.status);
142
175
  const wait = transient ? retryAfterMs(response.headers?.get?.("retry-after")) : undefined;
143
176
  const ids = [requestId ? `request ${requestId}` : "", rayId ? `Ray ID ${rayId}` : ""].filter(Boolean).join(", ");
144
177
  return {
145
178
  ok: false,
146
179
  ...(transient ? { transient: true } : {}),
180
+ ...(permanent ? { permanent: true } : {}),
181
+ ...fromFunction,
182
+ ...(rayId ? { rayId } : {}),
147
183
  // A refused key. Only a cue to ask the board whether Remove took it
148
184
  // away (lib/selfUninstall.mjs); never proof on its own (#4978).
149
185
  ...(response.status === 401 ? { unauthorized: true } : {}),
@@ -154,18 +190,29 @@ async function call(op, body = {}, options = {}) {
154
190
  : `board-runner answered ${response.status}${detail ? `: ${detail}` : ""}${ids ? ` (${ids})` : ""}${wait !== undefined ? `; retry after ${Math.ceil(wait / 1000)}s` : ""}`,
155
191
  };
156
192
  }
157
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
193
+ if (!isObject(payload)) {
158
194
  return { ok: false, error: `board-runner answered with unreadable JSON: ${text.slice(0, 400)}` };
159
195
  }
160
196
  if (payload.ok === false) {
161
197
  // `refused`: the function answered no. `retry` marks the refusals that
162
198
  // only hold while other work runs; the rest stay refused.
163
- return { ok: false, refused: true, ...(payload.retry === true ? { retry: true } : {}), error: errorDetail(payload.error) ?? "board-runner refused the request." };
199
+ return { ok: false, refused: true, fromFunction: true, ...(payload.retry === true ? { retry: true } : {}), error: errorDetail(payload.error) ?? "board-runner refused the request." };
164
200
  }
165
201
  if (payload.ok !== true) return { ok: false, error: "board-runner returned an incomplete response." };
166
202
  return payload;
167
203
  }
168
204
 
205
+ /** Does the function itself answer `op` at this address right now? The same
206
+ * op with only a run id: it writes nothing (the function refuses it as
207
+ * incomplete), and it carries none of the text a firewall might block. A
208
+ * JSON answer, yes or no, means the address is open, so a 403 on the full
209
+ * body was about its content (#8648). A page, a timeout or no network means
210
+ * it is not. */
211
+ export async function reachable({ op, runId }, options = {}) {
212
+ const out = await call(op, { runId }, options);
213
+ return out.ok === true || out.fromFunction === true;
214
+ }
215
+
169
216
  // ---------- one function per op, per the Move 2 contract ----------
170
217
 
171
218
  /** `register {runnerId, host, platform, presence, projects:[{path, name?}]}`
@@ -18,6 +18,7 @@ import { OUT_OF_TIME, runCodingChecks } from "./codingChecks.mjs";
18
18
  import { beforePicture, checkPage } from "./pagePictures.mjs";
19
19
  import { retainRunEvents, deliverRunEvents, isMissingConversation } from "./runnerSettlement.mjs";
20
20
  import { changedFiles } from "./worktree.mjs";
21
+ import { folderState } from "./folderState.mjs";
21
22
 
22
23
  /** The two notes a fresh session gets in place of a conversation that could
23
24
  * not be resumed: its worktree is gone, or Claude Code has no record of it. */
@@ -155,6 +156,15 @@ async function runStarted(ctx, state, { timing, receipt, preparation, finish })
155
156
  };
156
157
 
157
158
  if (settings.stopped?.has(id)) return await finish({ status: "stopped", result: settings.leaseLost?.has(id) ? "STOPPED\n\nRunner connection expired before the process was started.\n" : "STOPPED\n\nStopped by user request before the process was started.\n", finished_at: new Date().toISOString() });
159
+ // Checking is part of a finished run, before its one closing reply and
160
+ // cleanup. Drafts and chat turns never start scripts or an automatic edit,
161
+ // and nor does a read-only ask (#8611): it changed nothing, so there is
162
+ // nothing to check, and its folder is the person's own checkout.
163
+ const checksFollow = !isChat && request.planMode !== "draft" && request.readOnly !== true;
164
+ // A run in the folder itself has no copy to compare with its base, so its
165
+ // state at the start is kept to tell, at the end, whether it changed
166
+ // anything (#8611). null: not a git checkout, or git could not say.
167
+ const startState = checksFollow && !made.isolated ? await folderState(made.cwd) : null;
158
168
  preparation.complete();
159
169
  timing.launched();
160
170
  const firstRunStartedAt = Date.now();
@@ -173,12 +183,16 @@ async function runStarted(ctx, state, { timing, receipt, preparation, finish })
173
183
  let { outcome, sessionIdSource } = retried;
174
184
  const { resumeNotFound } = retried;
175
185
 
176
- // Checking is part of this run, before its one closing reply and cleanup.
177
- // Drafts and chat turns must never start scripts or an automatic edit.
178
- if (outcome.ok && !isChat && request.planMode !== "draft" && !await stopCheck()) {
179
- ({ outcome, sessionIdSource } = await checkAndRepair(ctx, state, {
180
- outcome, sessionIdSource, stopCheck, firstRunStartedAt, childEnvObj, onChunk, runFn, makeRunOpts, remainingBudget,
181
- }));
186
+ if (outcome.ok && checksFollow && !await stopCheck()) {
187
+ if (startState !== null && await folderState(made.cwd) === startState) {
188
+ // Nothing to check: the row says nothing about checks (#4094's empty result).
189
+ log(`[${id}] no checks: the run changed nothing in ${made.cwd}`);
190
+ outcome.result = { checks: [], filesChanged: false, fixAttempted: false };
191
+ } else {
192
+ ({ outcome, sessionIdSource } = await checkAndRepair(ctx, state, {
193
+ outcome, sessionIdSource, stopCheck, firstRunStartedAt, childEnvObj, onChunk, runFn, makeRunOpts, remainingBudget,
194
+ }));
195
+ }
182
196
  }
183
197
 
184
198
  timing.exited();
@@ -2,7 +2,7 @@
2
2
  * status write; watch/startup replay the same receipt until acknowledged. */
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { mkdir, open, readdir, readFile, rename, unlink } from "node:fs/promises";
5
- import { join } from "node:path";
5
+ import { basename, dirname, join } from "node:path";
6
6
  import { viewableHome } from "./registry.mjs";
7
7
  import * as defaultApi from "./runnerApi.mjs";
8
8
 
@@ -22,13 +22,11 @@ export async function prepareCompletionStore(project, settings) {
22
22
  return dir;
23
23
  }
24
24
 
25
- async function writeReceipt(project, runId, patch, settings, events) {
26
- const dir = await prepareCompletionStore(project, settings);
27
- const path = join(dir, `${digest(runId)}${events ? `-events-${events[0].seq}` : ""}.json`);
25
+ async function writeJson(path, value) {
28
26
  const temporary = `${path}.${randomUUID()}.tmp`;
29
27
  const handle = await open(temporary, "wx", 0o600);
30
28
  try {
31
- await handle.writeFile(JSON.stringify({ projectId: project.id, runId, ...(settings.runGeneration ? { generation: settings.runGeneration } : {}), ...(events ? { events } : { patch }) }));
29
+ await handle.writeFile(JSON.stringify(value));
32
30
  await handle.sync();
33
31
  } finally { await handle.close(); }
34
32
  try { await rename(temporary, path); }
@@ -36,27 +34,138 @@ async function writeReceipt(project, runId, patch, settings, events) {
36
34
  return path;
37
35
  }
38
36
 
37
+ async function writeReceipt(project, runId, patch, settings, events, extra = {}) {
38
+ const dir = await prepareCompletionStore(project, settings);
39
+ const path = join(dir, `${digest(runId)}${events ? `-events-${events[0].seq}` : ""}.json`);
40
+ return writeJson(path, { projectId: project.id, runId, ...(settings.runGeneration ? { generation: settings.runGeneration } : {}), ...(events ? { events } : { patch }), ...extra });
41
+ }
42
+
43
+ // SET ASIDE (#8648). A saved event or result the server will never take must
44
+ // not stop the computer taking asks. It moves here, kept for support, and a
45
+ // stand-in takes its place under the same name, so the log keeps its marker
46
+ // and the run row still ends. Admission reads only the folder above.
47
+ export const SET_ASIDE = "set-aside";
48
+ export const MAX_REFUSALS = 5;
49
+ export const SKIPPED_LINE = "One log line could not be saved and was skipped.";
50
+ export const RESULT_NOT_SAVED = "The run finished, but its answer could not be saved here. It is kept on the computer.";
51
+
52
+ const acknowledged = (last) => Boolean(last?.ok || last?.error === "runner ownership lost");
53
+
54
+ /** What a failed delivery means for its saved file:
55
+ * - "content": the function is reachable and will not take this body. A 4xx
56
+ * counts only when the function answered it, or a tiny call to the same
57
+ * op and address in this flush comes back as the function's own JSON.
58
+ * Otherwise a firewall may be blocking the whole computer, and nothing is
59
+ * replaced while that lasts.
60
+ * - "count": the function said no (not a `retry` no). Taken after
61
+ * MAX_REFUSALS flushes.
62
+ * - "wait": the network, a 5xx, a 429, a refused sign-in or a 403 from a
63
+ * closed address. Retried as before and never counted. */
64
+ async function refusalKind(last, record, settings) {
65
+ if (!last || last.ok || last.transient || last.retry || last.unauthorized) return "wait";
66
+ if (last.permanent) {
67
+ if (last.fromFunction) return "content";
68
+ const api = settings.runnerApi ?? defaultApi;
69
+ if (typeof api.reachable !== "function") return "wait";
70
+ const open = await api.reachable({ op: record.events ? "events" : "update", runId: record.runId }, { env: settings.env, fetchImpl: settings.fetchImpl }).catch(() => false);
71
+ return open === true ? "content" : "wait";
72
+ }
73
+ return last.refused ? "count" : "wait";
74
+ }
75
+
76
+ /** The record that takes a refused one's place, or null when the refused one
77
+ * was already the last stand-in. Ids, seq and lease generation are kept. */
78
+ function standInFor(record) {
79
+ const base = { projectId: record.projectId, runId: record.runId, ...(record.generation ? { generation: record.generation } : {}) };
80
+ if (record.events) return record.standIn ? null : { ...base, events: [{ seq: record.events[0].seq, kind: "cut", text: SKIPPED_LINE }], standIn: "cut" };
81
+ if (!record.standIn) return { ...base, patch: { ...record.patch, result: RESULT_NOT_SAVED }, standIn: "note" };
82
+ // The note refused too: only what ends the run row, so the computer's
83
+ // running count frees (#5732).
84
+ if (record.standIn === "note") {
85
+ const { status, finished_at } = record.patch;
86
+ return { ...base, patch: { status, ...(finished_at ? { finished_at } : {}), result: RESULT_NOT_SAVED }, standIn: "bare" };
87
+ }
88
+ return null;
89
+ }
90
+
91
+ const describe = (record) => record.events ? `event seq ${record.events[0].seq}${record.standIn ? " (its skipped-line marker)" : ""}` : record.standIn ? `result (${record.standIn} stand-in)` : "result";
92
+ const keepRecord = ({ refusals: _refusals, ...rest }) => rest;
93
+
94
+ /** Keep the refused record in set-aside/, then write its stand-in over the
95
+ * same name. Always in that order, so a crash anywhere replays cleanly:
96
+ * either the original is still in place and is set aside again, or the
97
+ * stand-in is. Returns the stand-in, or null when there is none to send. */
98
+ async function setAside(path, record, log, last) {
99
+ const asideDir = join(dirname(path), SET_ASIDE);
100
+ await mkdir(asideDir, { recursive: true, mode: 0o700 });
101
+ const name = basename(path);
102
+ const next = standInFor(record);
103
+ const why = `${last?.error ?? "refused"}${last?.rayId && !String(last?.error).includes(last.rayId) ? ` (Ray ID ${last.rayId})` : ""}`;
104
+ if (!record.standIn) await writeJson(join(asideDir, name), keepRecord(record));
105
+ if (next) await writeJson(path, next);
106
+ else await rename(path, join(asideDir, name.replace(/\.json$/, `-${record.standIn}.json`))).catch(error => { if (error.code !== "ENOENT") throw error; });
107
+ log(`[${record.runId}] set aside ${describe(record)}, kept in ${SET_ASIDE}/: ${why}`);
108
+ return next;
109
+ }
110
+
111
+ async function savedRefusals(path) {
112
+ try { return Number(JSON.parse(await readFile(path, "utf8")).refusals) || 0; }
113
+ catch (error) { if (error.code === "ENOENT") return null; throw error; }
114
+ }
115
+
116
+ async function send(api, record, options) {
117
+ try {
118
+ return record.events
119
+ ? await api.events({ runId: record.runId, events: record.events }, options)
120
+ : await api.update({ runId: record.runId, patch: record.patch, ...(record.generation ? { generation: record.generation } : {}) }, options);
121
+ } catch (error) { return { ok: false, error: error.message }; }
122
+ }
123
+
39
124
  const replaying = new Map();
40
125
  async function deliver(path, record, settings, log, attempts) {
41
126
  if (replaying.has(path)) return replaying.get(path);
42
127
  const task = (async () => {
43
128
  const api = settings.runnerApi ?? defaultApi;
44
129
  const options = { env: settings.env, fetchImpl: settings.fetchImpl };
45
- let last;
46
- for (let attempt = 0; attempt < attempts; attempt += 1) {
47
- try { last = record.events
48
- ? await api.events({ runId: record.runId, events: record.events }, options)
49
- : await api.update({ runId: record.runId, patch: record.patch, ...(record.generation ? { generation: record.generation } : {}) }, options); }
50
- catch (error) { last = { ok: false, error: error.message }; }
51
- if (last?.ok || last?.error === "runner ownership lost") {
52
- if (!last.ok) log(`[${record.runId}] discarded receipt from an older lease generation`);
53
- await unlink(path).catch(error => { if (error.code !== "ENOENT") log(`[${record.runId}] completion acknowledged; local cleanup will retry: ${error.message}`); });
54
- return true;
130
+ let current = record;
131
+ for (;;) {
132
+ let last;
133
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
134
+ last = await send(api, current, options);
135
+ if (acknowledged(last)) {
136
+ if (!last.ok) log(`[${current.runId}] discarded receipt from an older lease generation`);
137
+ await unlink(path).catch(error => { if (error.code !== "ENOENT") log(`[${current.runId}] completion acknowledged; local cleanup will retry: ${error.message}`); });
138
+ return true;
139
+ }
140
+ // Sending the same body again at once cannot change a refusal.
141
+ if (last?.permanent || (last?.refused && !last.retry)) break;
142
+ if (attempt + 1 < attempts) await new Promise(resolve => setTimeout(resolve, (settings.completionRetryMs ?? 250) * (attempt + 1)));
143
+ }
144
+ const kind = await refusalKind(last, current, settings);
145
+ let refusals = 0;
146
+ if (kind === "count") {
147
+ const saved = await savedRefusals(path);
148
+ if (saved === null) return true; // Another delivery already took it.
149
+ refusals = saved + 1;
55
150
  }
56
- if (attempt + 1 < attempts) await new Promise(resolve => setTimeout(resolve, (settings.completionRetryMs ?? 250) * (attempt + 1)));
151
+ if (kind === "content" || refusals >= MAX_REFUSALS) {
152
+ let next;
153
+ try { next = await setAside(path, current, log, last); }
154
+ catch (error) {
155
+ // Never let a failed set-aside reach the run's own error path: the
156
+ // saved receipt stays as it is and the next flush tries again.
157
+ log(`[${current.runId}] completion retained for retry; could not set it aside: ${error.message}`);
158
+ return false;
159
+ }
160
+ if (!next) return true;
161
+ current = next;
162
+ attempts = 1;
163
+ continue;
164
+ }
165
+ if (kind === "count") await writeJson(path, { ...current, refusals });
166
+ log(`[${current.runId}] completion retained for retry: ${last?.error ?? "update was not acknowledged"}`);
167
+ return false;
57
168
  }
58
- log(`[${record.runId}] completion retained for retry: ${last?.error ?? "update was not acknowledged"}`);
59
- return false;
60
169
  })();
61
170
  replaying.set(path, task);
62
171
  try { return await task; } finally { replaying.delete(path); }
@@ -68,21 +177,35 @@ export async function retainRunEvents(project, runId, events, settings) {
68
177
  for (const event of events) await writeReceipt(project, runId, undefined, settings, [event]);
69
178
  }
70
179
 
180
+ /** The saved copy of a live event when there is one: after a set-aside it is
181
+ * the stand-in and carries its refusal count, and sending the streamer's
182
+ * original again would undo both (#8648). */
183
+ async function savedEvent(path, runId, event) {
184
+ try {
185
+ const saved = JSON.parse(await readFile(path, "utf8"));
186
+ if (saved?.runId === runId && Array.isArray(saved.events) && saved.events.length === 1 && saved.events[0]?.seq === event.seq) return saved;
187
+ } catch { /* Not saved (or unreadable): send the streamer's own row. */ }
188
+ return null;
189
+ }
190
+
71
191
  export async function deliverRunEvents(project, runId, events, settings, log = () => {}) {
72
192
  for (const event of events) {
73
193
  const path = join(completionDirectory(project, settings), `${digest(runId)}-events-${event.seq}.json`);
74
- if (!await deliver(path, { projectId: project.id, runId, events: [event] }, settings, log, 1)) return { ok: false };
194
+ const record = await savedEvent(path, runId, event) ?? { projectId: project.id, runId, events: [event] };
195
+ if (!await deliver(path, record, settings, log, 1)) return { ok: false };
75
196
  }
76
197
  return { ok: true };
77
198
  }
78
199
 
79
- export async function settleRun(project, runId, patch, settings, log = () => {}, { deferDelivery = false } = {}) {
200
+ export async function settleRun(project, runId, patch, settings, log = () => {}, { deferDelivery = false, carried } = {}) {
80
201
  if (!terminal.has(patch.status)) throw new Error("A terminal receipt requires a terminal status.");
81
- const record = { projectId: project.id, runId, patch, ...(settings.runGeneration ? { generation: settings.runGeneration } : {}) };
202
+ // `carried`: a memory receipt's stand-in state and refusal count (#8648).
203
+ const extra = { ...(carried?.standIn ? { standIn: carried.standIn } : {}), ...(carried?.refusals ? { refusals: carried.refusals } : {}) };
204
+ const record = { projectId: project.id, runId, patch, ...(settings.runGeneration ? { generation: settings.runGeneration } : {}), ...extra };
82
205
  const memoryKey = join(completionDirectory(project, settings), digest(runId));
83
206
  memoryReceipts.set(memoryKey, record);
84
207
  let path;
85
- try { path = await writeReceipt(project, runId, patch, settings); }
208
+ try { path = await writeReceipt(project, runId, patch, settings, undefined, extra); }
86
209
  catch (error) {
87
210
  // Never replace a completed result with a generic execution error when
88
211
  // local storage fails. Try the server while retaining the original patch.
@@ -96,6 +219,22 @@ export async function settleRun(project, runId, patch, settings, log = () => {},
96
219
  memoryReceipts.delete(memoryKey);
97
220
  return { id: runId, state: patch.status === "done" ? "done" : "failed", patch };
98
221
  }
222
+ // The same rule as a saved file: a body the server will never take is
223
+ // replaced by its stand-in, so it cannot block claims for good.
224
+ const kind = await refusalKind(result, record, settings);
225
+ const refusals = kind === "count" ? (record.refusals ?? 0) + 1 : 0;
226
+ if (kind === "content" || refusals >= MAX_REFUSALS) {
227
+ const next = standInFor(record);
228
+ // The original answer stays in memory until set-aside/ can hold it:
229
+ // every flush tries to write it there, so recovered storage keeps it.
230
+ if (!record.standIn) memoryAside.set(memoryKey, keepRecord(record));
231
+ log(`[${runId}] set aside ${describe(record)} in memory; local storage is unavailable: ${result?.error ?? "refused"}`);
232
+ if (!next) {
233
+ memoryReceipts.delete(memoryKey);
234
+ return { id: runId, state: patch.status === "done" ? "done" : "failed", patch };
235
+ }
236
+ memoryReceipts.set(memoryKey, next);
237
+ } else if (kind === "count") memoryReceipts.set(memoryKey, { ...record, refusals });
99
238
  log(`[${runId}] completion retained in memory; local storage is unavailable: ${error.message}`);
100
239
  return { id: runId, state: "pending-sync", patch };
101
240
 
@@ -108,12 +247,28 @@ export async function settleRun(project, runId, patch, settings, log = () => {},
108
247
  return { id: runId, state: synced ? (patch.status === "done" ? "done" : "failed") : "pending-sync", patch };
109
248
  }
110
249
 
250
+ /** Originals set aside while local storage was down (#8648). They block no
251
+ * claim; each flush writes the ones for this folder to set-aside/. */
252
+ const memoryAside = new Map();
253
+ async function saveMemoryAside(dir, log) {
254
+ for (const [key, record] of [...memoryAside]) {
255
+ if (key !== join(dir, digest(record.runId))) continue;
256
+ try {
257
+ await mkdir(join(dir, SET_ASIDE), { recursive: true, mode: 0o700 });
258
+ await writeJson(join(dir, SET_ASIDE, `${digest(record.runId)}.json`), record);
259
+ memoryAside.delete(key);
260
+ log(`[${record.runId}] kept the set-aside result in ${SET_ASIDE}/ now that local storage works`);
261
+ } catch { /* Storage still down: the next flush tries again. */ }
262
+ }
263
+ }
264
+
111
265
  export async function flushCompletions(project, settings, log = () => {}) {
112
266
  const dir = completionDirectory(project, settings);
113
267
  let complete = true;
268
+ await saveMemoryAside(dir, log);
114
269
  for (const [key, record] of [...memoryReceipts]) {
115
270
  if (key !== join(dir, digest(record.runId))) continue;
116
- const result = await settleRun(project, record.runId, record.patch, { ...settings, runGeneration: record.generation }, log);
271
+ const result = await settleRun(project, record.runId, record.patch, { ...settings, runGeneration: record.generation }, log, { carried: record });
117
272
  if (result.state === "pending-sync") complete = false;
118
273
  }
119
274
  let names;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "viewable-one",
3
- "version": "0.12.9",
3
+ "version": "0.12.11",
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",