viewable-one 0.12.10 → 0.12.12

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,40 @@ package.
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [0.12.12] - 2026-11-26
17
+
18
+ ### Fixed
19
+
20
+ - A run whose plan reads apps through Viewable is told one paged read and one
21
+ way to land it (#8675, #8672). Walk c's "status of each issue with
22
+ sub-issues" read 47 parents one at a time (105 reads, 15 minutes) and typed
23
+ the rows into a `propose` snippet, which landed as an empty circle in its
24
+ own group. The spawn preamble (`appReadRule`) now says to read items with
25
+ their children, or every row of a list, once with `read_all_rows { tool,
26
+ args, with_children }` and never to draw a read's rows as a snippet;
27
+ `drawnCardRule` applies only to what no read holds (files, the web); and the
28
+ run's list of board tools names `set_live_card`. Claude Code and Codex get
29
+ the same words. The chat-turn rules are unchanged.
30
+
31
+ ## [0.12.11] - 2026-11-25
32
+
33
+ ### Fixed
34
+
35
+ - A computer no longer stops taking asks when the server's firewall refuses
36
+ one of a run's saved log lines or its result (#8648). A log line that quoted
37
+ code such as `require('fs').writeFileSync(` got Cloudflare's 403 page, and
38
+ the runner kept it to send forever while it claimed nothing. Now the calls
39
+ that carry a run's own text (`events`, `update`, `resume`, `opResult`) go
40
+ base64-encoded, which `board-runner` unwraps; an older function that answers
41
+ `Unknown op ""` gets the plain body once and is remembered. When the
42
+ function itself is reachable (it answered, or a tiny call to the same op in
43
+ the same flush got its JSON back) and still will not take a saved line, the
44
+ line moves to `run-completions/<folder>/set-aside/` and a skipped-line
45
+ marker takes its place at the same seq. A refused result is kept there too,
46
+ and a short note ends the run instead. A whole-computer block, the network,
47
+ a 5xx or a 429 are retried as before and never set anything aside. Each set
48
+ aside writes one `runner.log` line with the run id, seq and Ray ID.
49
+
16
50
  ## [0.12.10] - 2026-11-25
17
51
 
18
52
  ### Fixed
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:
package/lib/agents.mjs CHANGED
@@ -1001,6 +1001,7 @@ export function preambleFor(agent, { workplace, computerApps, boardServerKey, re
1001
1001
  // Only Claude Code and Codex, with the same words (#7581).
1002
1002
  const apps = ["claude", "codex"].includes(agentFor(agent)) ? plannedReadApps(readApps) : [];
1003
1003
  const appRead = spec.boardTool("app_read");
1004
+ const setLiveCard = spec.boardTool("set_live_card");
1004
1005
  return (
1005
1006
  "You were spawned from a canvas by a person who is not watching a terminal. " +
1006
1007
  (readOnly === true ? READ_ONLY_WORKPLACE : workplace ?? "You are in your own git worktree: commit your work on this branch, never " +
@@ -1025,10 +1026,11 @@ export function preambleFor(agent, { workplace, computerApps, boardServerKey, re
1025
1026
  // A refusal stops the run and asks; it never sends it to another login (#6995).
1026
1027
  refusalRule(ask) +
1027
1028
  // A table ask lands as a drawn card, never as words saying it was made (#8102).
1028
- (apps.length > 0 ? appReadRule(appRead, spec.boardTool("set_live_card"), apps) : "") +
1029
- drawnCardRule(spec.boardTool("propose")) +
1029
+ (apps.length > 0 ? appReadRule(appRead, setLiveCard, apps) : "") +
1030
+ drawnCardRule(spec.boardTool("propose"), { readApps: apps.length > 0 }) +
1031
+ // A run that reads apps lands its reads with set_live_card, so the list names it (#8672).
1030
1032
  `Your board tools are named ${spec.boardTool("get_board")}, ` +
1031
- `${spec.boardTool("get_node")}, ${spec.boardTool("propose")}, ${ask}${apps.length > 0 ? `, ${appRead}` : ""} and ${report}.\n\n` +
1033
+ `${spec.boardTool("get_node")}, ${spec.boardTool("propose")}, ${ask}${apps.length > 0 ? `, ${appRead}, ${setLiveCard}` : ""} and ${report}.\n\n` +
1032
1034
  // brief 23 ruling 4a (2026-09-07): the app derives the run's structure
1033
1035
  // - its steps, decisions and waiting state - from this session's own
1034
1036
  // log, and this preamble is the one place every session reads. So the
@@ -1084,9 +1086,14 @@ function appReadRule(appRead, setLiveCard, apps) {
1084
1086
  "command-line tool, a script, a web request or a login on this computer (no gh, no curl, no app's own CLI), " +
1085
1087
  "and the rule about the person's own apps on this computer does not apply to these. " +
1086
1088
  "Each read answers the app's rows and a read_ref that names the read for ten minutes. " +
1089
+ // ONE READ, NOT ONE PER ITEM (#8675): walk c's card 1 read 47 parents one at a time, 105 reads in 15 minutes.
1090
+ "For each item with its child items, or every row of a list, read once with the tool read_all_rows " +
1091
+ "{ tool, args, with_children } (tool being one of the app's read tools, args its filter, with_children true " +
1092
+ "for only the items that have child items, each with its children done and in all), never one read per item. " +
1087
1093
  `To put a table or chart of what you read on the board, land it with ${setLiveCard} ` +
1088
1094
  "{ shape: \"table\" or \"chart\", read_ref, columns }, columns being the fields to show, in order: the board " +
1089
- "builds the card from that read, so never type the rows in yourself; if the board refuses that, draw it as below. " +
1095
+ "builds the card from that read, so never type the rows in yourself and never draw them as a snippet; if the " +
1096
+ "board refuses that, draw it as below. " +
1090
1097
  `If ${appRead} is refused (the run was stopped or ran out of time, the app is not in the plan, the account is ` +
1091
1098
  "not on Pro), stop that part and say so in your answer, in the refusal's own words. Never read the app another way.\n\n"
1092
1099
  );
@@ -76,9 +76,20 @@ export function otherAppsRule() {
76
76
  // board: nothing told it that the board shows a table only as a drawn card.
77
77
  // The board tools now refuse that line (board-mcp claimCheck.mjs); this says
78
78
  // what to do first. `propose` is the engine's own tool name.
79
- export function drawnCardRule(propose) {
79
+ //
80
+ // ONE WAY TO LAND A READ (#8672). A run that read an app was told two ways at
81
+ // once: land the read with set_live_card (appReadRule), and draw any table as
82
+ // a propose snippet (this rule). Walk c's card 1 drew 47 rows by hand into a
83
+ // snippet, which lands as a circle whose table shows only when clicked. With
84
+ // `readApps` (the run reads apps through Viewable) this rule is for what no
85
+ // read holds (files, the web); the board refuses a table or chart snippet in
86
+ // a run that holds a read.
87
+ export function drawnCardRule(propose, { readApps = false } = {}) {
80
88
  return (
81
- "When the person asks for a table, chart, list, timeline or kanban, put it " +
89
+ (readApps
90
+ ? "When the person asks for a table, chart, list, timeline or kanban of something no read of yours holds " +
91
+ "(files, the web), put it "
92
+ : "When the person asks for a table, chart, list, timeline or kanban, put it ") +
82
93
  `on the board as a drawn card: ${propose} an addIdea with a snippet (x-table, ` +
83
94
  `x-chart, x-list, x-timeline; get_library lists them). ` +
84
95
  "Never say you made one you did not draw; if you could not, say so.\n\n"
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?}]}`
@@ -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.10",
3
+ "version": "0.12.12",
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",