viewable-one 0.12.7 → 0.12.9

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/lib/registry.mjs CHANGED
@@ -75,6 +75,16 @@ export async function folderWasRemoved(folder, env = process.env) {
75
75
  return existsSync(removedPath(folder, env));
76
76
  }
77
77
 
78
+ /** The listed folders minus those the person removed. Only an explicit add
79
+ * clears the mark, so a stray write that puts a folder back in the list
80
+ * cannot bring it back to life: the watcher, the registration and the
81
+ * presence list all read through this (#8325). */
82
+ export async function withoutRemoved(listed, env = process.env) {
83
+ const kept = [];
84
+ for (const folder of listed) if (!(await folderWasRemoved(folder, env))) kept.push(folder);
85
+ return kept;
86
+ }
87
+
78
88
  // TEMPORARY FOLDERS ARE NEVER REGISTERED (QA 2026-10-01, ticket e7). An agent
79
89
  // once started a runner from its scratchpad, and "proof-project
80
90
  // (/private/tmp/claude-501/...)" sat in Settings > Connection for days. A
@@ -167,12 +177,31 @@ async function writeRegistry(folders, env = process.env) {
167
177
  await writeFileAtomic(registryPath(env), `${JSON.stringify(folders, null, 2)}\n`);
168
178
  }
169
179
 
180
+ // EVERY READ-MODIFY-WRITE OF THE LIST RUNS UNDER THE ONE REGISTRY LOCK (#8325).
181
+ // touchRegistry once read the list, waited, and wrote it back after a Forget
182
+ // had removed the folder, which restored it and made the daemon watch it again.
183
+ // The public writers below take the lock themselves. The lock is not
184
+ // reentrant, so a caller that already holds it (a Forget, a restore) calls the
185
+ // `...HoldingLock` twin of the same writer: the code is shared, only the
186
+ // locking differs.
187
+
188
+ function refuseScratchFolder(path, env) {
189
+ if (isScratchFolder(path, env)) throw new Error(`${path} is a temporary folder, and those are never registered. Run viewable init in the project folder itself.`);
190
+ }
191
+
170
192
  /** Add a folder. Idempotent by absolute path: running `init` twice in one
171
193
  * folder leaves one entry, and the second run is not an error. Returns
172
194
  * {folders, added}. */
173
195
  export async function addFolder(folder, env = process.env) {
196
+ // Refused before the lock, so a refused folder never touches the home.
197
+ refuseScratchFolder(resolve(folder), env);
198
+ return withRegistryLock(() => addFolderHoldingLock(folder, env), env);
199
+ }
200
+
201
+ /** addFolder for a caller that already holds the registry lock. */
202
+ export async function addFolderHoldingLock(folder, env = process.env) {
174
203
  const path = resolve(folder);
175
- if (isScratchFolder(path, env)) throw new Error(`${path} is a temporary folder, and those are never registered. Run viewable init in the project folder itself.`);
204
+ refuseScratchFolder(path, env);
176
205
  const folders = await readRegistry(env);
177
206
  // Adding is the person asking for the folder back (init, sync): the record
178
207
  // of its removal ends here, even when it is already listed.
@@ -189,7 +218,7 @@ export async function addFolder(folder, env = process.env) {
189
218
  export async function addFolderUnlessRemoved(folder, env = process.env) {
190
219
  return withRegistryLock(async () => {
191
220
  if (await folderWasRemoved(folder, env)) return null;
192
- return addFolder(folder, env);
221
+ return addFolderHoldingLock(folder, env);
193
222
  }, env);
194
223
  }
195
224
 
@@ -198,6 +227,11 @@ export async function addFolderUnlessRemoved(folder, env = process.env) {
198
227
  * which is how `viewable init` in a folder already watched gets the fresh beat
199
228
  * it waits for (#813 review). A registry that is not there stays absent. */
200
229
  export async function touchRegistry(env = process.env) {
230
+ return withRegistryLock(() => touchRegistryHoldingLock(env), env);
231
+ }
232
+
233
+ /** touchRegistry for a caller that already holds the registry lock. */
234
+ export async function touchRegistryHoldingLock(env = process.env) {
201
235
  const { folders, ok } = await readRegistryChecked(env);
202
236
  if (!ok || folders.length === 0) return false;
203
237
  await writeRegistry(folders, env);
@@ -208,6 +242,11 @@ export async function touchRegistry(env = process.env) {
208
242
  * never registered is not an error either - the end state is what was asked
209
243
  * for. */
210
244
  export async function removeFolder(folder, env = process.env) {
245
+ return withRegistryLock(() => removeFolderHoldingLock(folder, env), env);
246
+ }
247
+
248
+ /** removeFolder for a caller that already holds the registry lock. */
249
+ export async function removeFolderHoldingLock(folder, env = process.env) {
211
250
  const path = resolve(folder);
212
251
  const folders = await readRegistry(env);
213
252
  // Recorded even when it was not listed: the person asked for it gone.
@@ -223,6 +262,11 @@ export async function removeFolder(folder, env = process.env) {
223
262
  * the caller can log one line each (the sweep does). A folder that is gone is
224
263
  * gone: nothing here creates it back, and nothing exits over it. */
225
264
  export async function pruneMissing(env = process.env) {
265
+ return withRegistryLock(() => pruneMissingHoldingLock(env), env);
266
+ }
267
+
268
+ /** pruneMissing for a caller that already holds the registry lock. */
269
+ export async function pruneMissingHoldingLock(env = process.env) {
226
270
  const folders = await readRegistry(env);
227
271
  const kept = [];
228
272
  const dropped = [];
@@ -13,6 +13,7 @@ import { liveRuns, restartPass, RECOVERY_RECHECK_MS, RESTART_RECHECK_MS } from "
13
13
  import { orphanRecoveries } from "./runnerRecovery.mjs";
14
14
  import { flushCompletions } from "./runnerSettlement.mjs";
15
15
  import { SERVER_SWEEP_INTERVAL_MS, sweepDetachedServers } from "./serverSweep.mjs";
16
+ import { sweepIdleWorktrees } from "./worktreeSweep.mjs";
16
17
  import { createSharedPreviewService } from "./sharedPreview.mjs";
17
18
  import { createMemberPreviewTunnel } from "./memberPreview.mjs";
18
19
  import { beatPace } from "./runnerPace.mjs";
@@ -102,6 +103,19 @@ export function makeBeatLoop(w) {
102
103
  log(`dev server sweep failed: ${error instanceof Error ? error.message : String(error)}`);
103
104
  }
104
105
  };
106
+ // THE TREES BEFORE #8266 LEFT BEHIND, once when this watcher starts, after
107
+ // the restart pass so a run it carries on is live and not looked at
108
+ // (lib/worktreeSweep.mjs). A failure is tried again at the next start.
109
+ let treesSwept = false;
110
+ const sweepTrees = async () => {
111
+ if (treesSwept) return;
112
+ treesSwept = true;
113
+ try {
114
+ await (settings.sweepIdleWorktrees ?? sweepIdleWorktrees)(w.project, settings, { log });
115
+ } catch (error) {
116
+ log(`worktree sweep failed: ${error instanceof Error ? error.message : String(error)}`);
117
+ }
118
+ };
105
119
  // Recheck periodically too: the same watcher may lose touch and recover
106
120
  // more than once without restarting its own process (#1252).
107
121
  let restartDueAt = 0;
@@ -256,6 +270,7 @@ export function makeBeatLoop(w) {
256
270
  try { lateMessagesDueAt = nextLateLookAt(await resumeLateMessages(w.project, settings, log), settings); }
257
271
  catch (error) { opsFailed = true; log(`late answers: ${error.message}`); }
258
272
  }
273
+ if (flushed) await sweepTrees();
259
274
  await sweepServers();
260
275
  preview.tick();
261
276
  // Use the existing failure backoff while an answer is waiting, rather
@@ -110,28 +110,29 @@ export async function completeRequest(context, services = defaultServices) {
110
110
 
111
111
  const claudeSessionId = extractSessionIdFromLog(sessionIdSource ?? outcome.log ?? "");
112
112
 
113
- // A CHILD THAT NEVER RAN KEEPS NOTHING "FOR SESSION RESUME" (2026-09-20).
114
- // `outcome.spawnError` means `child.on("error")` fired in child.mjs -
115
- // this machine could not even start the binary (spawn ENOENT, most often)
116
- // - so the worktree `made` names was never touched: no commits, no
117
- // uncommitted changes, nothing a resume could possibly continue. Before
118
- // this, `isPersistent` alone decided the branch below, and a request that
119
- // carries a sessionId/resumeSessionId (every board-spawned session does)
120
- // took the "KEPT for session resume" literal unconditionally - so a run
121
- // that failed to start still held its worktree forever, and the very next
122
- // request on the same prompt was refused as "already has an active
123
- // session" against a tree with nothing in it. `cleanWorktree` is safe to
124
- // call here even though it is NOT normally called for a persistent
125
- // request: it inspects the tree's own git status before removing anything
126
- // (worktree.mjs's `cleanWorktreeImpl`), so a request that also happened to
127
- // fail AFTER doing real work is still `spawnError`-free by definition
128
- // (the child ran, so this branch is not reached) and never hits this path.
129
- const neverStarted = Boolean(outcome.spawnError);
130
- const cleaned = neverStarted
131
- ? await cleanWorktree(root, made, log, [])
132
- : isPersistent
133
- ? { removed: false, detail: `${made.detail}\nKEPT for session resume (persistent session).` }
134
- : await cleanWorktree(root, made, log, []);
113
+ // EVERY ENDED RUN ASKS `cleanWorktree`, A SESSION INCLUDED (#8266, ruling
114
+ // #470: unchanged goes, changed stays until Keep or Throw away). This used
115
+ // to skip the call for any run with a session id and log "KEPT for session
116
+ // resume" - and every board ask has one, so each ask on Your computer left
117
+ // a `.claude/worktrees/glytch-*` tree and a branch behind even when it
118
+ // changed nothing. `cleanWorktree` inspects the tree itself (worktree.mjs's
119
+ // `cleanWorktreeImpl`): commits or uncommitted changes keep it, a failed
120
+ // inspection keeps it, a chat tree is never touched. What a removal costs a
121
+ // session is the conversation Claude Code keeps per working directory,
122
+ // which an unchanged tree had nothing worth resuming for; a reply to it
123
+ // gets a fresh tree (runnerWorkspace.mjs), told by `worktreeRemoved` below.
124
+ //
125
+ // A child that never started (`outcome.spawnError`, 2026-09-20: spawn
126
+ // ENOENT) is the same call; its tree was never touched.
127
+ //
128
+ // ONE TREE IS NOT REMOVED EVEN WHEN NOTHING IN IT CHANGED: the one a
129
+ // detached dev server runs from (the session left a preview going, `server`
130
+ // above). Taking its folder away breaks the preview the person was shown.
131
+ // It stays, with Keep and Throw away, until the server's own sweep or Throw
132
+ // away ends it.
133
+ const cleaned = server && made.isolated && made.path
134
+ ? { removed: false, detail: `${made.detail}\nKEPT: a dev server it started is still running from this worktree.` }
135
+ : await cleanWorktree(root, made, log, []);
135
136
 
136
137
  const treeKept = !cleaned.removed && made.isolated && made.path;
137
138
  let sidecar;
@@ -173,6 +174,10 @@ export async function completeRequest(context, services = defaultServices) {
173
174
  // A chat turn is the one non-isolated case that still needs the path:
174
175
  // it IS the room's cwd, and the next turn is sent back there.
175
176
  ...(cleaned.removed || (!made.isolated && !isChat) ? {} : { worktreePath: made.path ?? made.cwd }),
177
+ // Says WHY a reply finds no tree (#8266): the unchanged tree this run
178
+ // ended in (its own, or an earlier run's it reused) was removed, so a
179
+ // continuation naming that path may start a fresh one (runnerGates.mjs).
180
+ ...(cleaned.removed && made.path ? { worktreeRemoved: made.path } : {}),
176
181
  ...(from ? { fromId: from } : {}),
177
182
  expired: isPersistent ? (!claudeSessionId || outcome.ok !== true) : undefined,
178
183
  ...(summary?.line ? { worktreeSummary: summary.line } : {}),
@@ -210,6 +215,7 @@ export async function completeRequest(context, services = defaultServices) {
210
215
  preview: Number.isFinite(Number(server?.port)) ? `http://localhost:${Number(server.port)}` : undefined,
211
216
  });
212
217
  resultLanded = receipt?.landed === true;
218
+ if (typeof receipt?.refusal === "string") log(`[${id}] the closing reply did not land on the board: ${receipt.refusal.slice(0, 500)}`);
213
219
  } catch (error) {
214
220
  log(`[${id}] could not comment the outcome onto the board: ${error instanceof Error ? error.message : String(error)}`);
215
221
  }
@@ -15,8 +15,11 @@ import * as runnerApiModule from "./runnerApi.mjs";
15
15
  import { callTool as hostedCallToolDefault } from "./hosted.mjs";
16
16
  import { runnerMcpUrlFrom } from "./mcpjson.mjs";
17
17
  import { hostedConfig, hostedToken } from "./auth.mjs";
18
- import { computerAppsOffRule, otherAppsRule } from "./conversationRules.mjs";
19
- import { acceptsMessages, agentFor, commandFor, isPersistentRequest, preambleFor } from "./agents.mjs";
18
+ import { acceptsMessages, agentFor, boardRunKey, chatRulesFor, commandFor, isPersistentRequest, preambleFor } from "./agents.mjs";
19
+ import { claudeAppServers } from "./computerApps.mjs";
20
+ import { mkdtemp, writeFile } from "node:fs/promises";
21
+ import { tmpdir } from "node:os";
22
+ import { join } from "node:path";
20
23
  import { getRepoMap, formatRepoPrimer } from "./repomap.mjs";
21
24
  import { buildAttemptsSectionFromRows } from "./compose.mjs";
22
25
  import { imageInspectionInstruction } from "./imageAttachments.mjs";
@@ -84,29 +87,43 @@ export async function executeRequest(project, run, settings, log, timing, receip
84
87
  // and its `runnerApi` calls, not a signal file).
85
88
  const isChat = isChatTurn(request);
86
89
 
87
- const ctx = { eventSeq: run.event_seq, project, root, id, request, isChat, runnerApi, hostedEnv, rowsOpts, session, claimedAt, boardId, settings, log };
90
+ // A run an automation filed carries its `schedule_id` (the claimed row is the whole `runs` row).
91
+ const fromAutomation = typeof run.schedule_id === "string" && run.schedule_id !== "";
92
+ const ctx = { eventSeq: run.event_seq, project, root, id, request, isChat, fromAutomation, runnerApi, hostedEnv, rowsOpts, session, claimedAt, boardId, settings, log };
88
93
  const admitted = await admitRequest(ctx, preparation);
89
94
  if ("patch" in admitted) return finish(admitted.patch);
90
95
  const prepared = await prepareRun(ctx, admitted, receipt, preparation);
91
96
  if ("patch" in prepared) return finish(prepared.patch);
92
97
  const state = { ...admitted, ...prepared };
98
+ // Folders this run made for its MCP config files; startRun removes them.
99
+ state.tempDirs = [];
93
100
  state.planRun = makePlanRun(ctx, state);
94
101
  return startRun(ctx, state, { timing, receipt, preparation, finish });
95
102
  }
96
103
 
97
104
  /** The hosted board this run reports to, and the worktree it runs in. `{
98
105
  * patch }` when the workspace refused; otherwise what `startRun` needs. */
99
- async function prepareRun({ project, root, id, request, isChat, runnerApi, hostedEnv, rowsOpts, session, claimedAt, settings, log }, { chatCwd, isResume, from, ownTreePath }, receipt, preparation) {
106
+ async function prepareRun({ project, root, id, request, isChat, runnerApi, hostedEnv, rowsOpts, session, claimedAt, boardId, settings, log }, { chatCwd, chatInFolder, isResume, from, ownTreePath, ownTreeRemoved }, receipt, preparation) {
100
107
  const hostedBoard = await hostedConfig({ env: hostedEnv });
101
108
  const childMcpUrl = runnerMcpUrlFrom(hostedBoard, hostedEnv, (message) => log(`[${id}] ${message}`));
102
109
  // The runner's permission checks and collect_session (including the final
103
110
  // sweep) use the same direct endpoint as its child. Keep the hosted
104
111
  // transport's refresh/deadline/cancellation logic; only reroute MCP posts,
105
112
  // never OAuth discovery or refresh requests made through the same fetch.
106
- const hostedCallTool = settings.hostedCallTool ?? ((name, args, options) => hostedCallToolDefault(name, args, {
113
+ const transport = settings.hostedCallTool ?? ((name, args, options) => hostedCallToolDefault(name, args, {
107
114
  ...options,
108
115
  mcpUrl: childMcpUrl, fetchImpl: settings.fetchImpl,
109
116
  }));
117
+ // EVERY HOSTED CALL THE RUNNER MAKES FOR THIS RUN NAMES THE RUN'S BOARD
118
+ // (#7489). The closing reply, the answer poll, the late-row sweep and a
119
+ // refusal note send no board_id, and since #5149 the server refuses such a
120
+ // write inside a 200 when the account has two or more open boards, so the
121
+ // run's answer never landed. The child already gets the same id as
122
+ // X-Glytch-Board; permission asks pinned it on their own. A row with no
123
+ // board id sends no header, as before.
124
+ const hostedCallTool = boardId
125
+ ? (name, args, options) => transport(name, args, { sessionBoardId: boardId, ...options })
126
+ : transport;
110
127
  const boardToken = await hostedToken({ env: hostedEnv, fetchImpl: settings.fetchImpl, log });
111
128
  preparation.check();
112
129
  if (!boardToken) {
@@ -128,8 +145,8 @@ async function prepareRun({ project, root, id, request, isChat, runnerApi, hoste
128
145
  }
129
146
  };
130
147
  const workspace = await prepareRequestWorkspace({
131
- root, id, request, isResume, session, from, log, isChat, chatCwd, claimedAt, ownTreePath,
132
- otherRunningCount, preparation, retainSidecar,
148
+ root, id, request, isResume, session, from, log, isChat, chatCwd, chatInFolder, claimedAt, ownTreePath, ownTreeRemoved,
149
+ otherRunningCount, preparation, retainSidecar, callTool: hostedCallTool,
133
150
  updateSidecarEarly: (sidecar) => {
134
151
  preparation.check();
135
152
  retainSidecar(sidecar);
@@ -156,9 +173,36 @@ async function prepareRun({ project, root, id, request, isChat, runnerApi, hoste
156
173
 
157
174
  /** The prompt, the command and its arguments for one try of this run: the
158
175
  * first, a fresh retry when the resume was not found, or the one fix. */
159
- function makePlanRun({ project, root, id, request, isChat, runnerApi, hostedEnv, session, boardId, settings, log }, { referenceImages, from, agent, resolvedBinPath, made, useStreaming, boardToken, childMcpUrl }) {
176
+ function makePlanRun({ project, root, id, request, isChat, runnerApi, hostedEnv, session, boardId, settings, log }, { referenceImages, from, agent, resolvedBinPath, made, useStreaming, boardToken, childMcpUrl, tempDirs }) {
160
177
  return async ({ resumeId, note, fixing = false }) => {
161
178
  const fresh = resumeId === "";
179
+ // ONE BOARD SERVER PER RUN (#7550). Claude's per-launch board key is made
180
+ // here, so the prompt names the run's own tools by it, and with the
181
+ // person's apps on, their own servers are read now: every Viewable board
182
+ // server is left out (computerApps.mjs claudeAppServers). A list that
183
+ // cannot be read runs this launch with the apps off, and says so.
184
+ const isClaude = agentFor(agent) === "claude";
185
+ const boardServerKey = isClaude ? boardRunKey() : undefined;
186
+ // A run that only reads (#8261) never loads the person's own apps.
187
+ let computerApps = request.computerApps === true && request.readOnly !== true;
188
+ let appServers;
189
+ const notices = [];
190
+ if (isClaude && computerApps && request.planMode !== "draft") {
191
+ try {
192
+ const read = await claudeAppServers({ cwd: made.cwd, root, env: settings.env ?? process.env });
193
+ appServers = read.servers;
194
+ if (read.dropped.length) {
195
+ log(`[${id}] left out of this run, another Viewable board server: ${read.dropped.join(", ")}`);
196
+ // The person's own app named `board` or `viewable` would vanish with
197
+ // no visible reason (#7591), as Codex's (codexApps.mjs notice) does not.
198
+ notices.push(`${read.dropped.join(", ")} ${read.dropped.length === 1 ? "was" : "were"} turned off for this run because a run uses only its own Viewable board.`);
199
+ }
200
+ } catch {
201
+ computerApps = false;
202
+ log(`[${id}] could not read the apps set up in Claude Code; this run goes with them off`);
203
+ notices.push("Couldn't read the apps set up in Claude Code, so this run went without them. Check your apps in Claude Code, then try again.");
204
+ }
205
+ }
162
206
  // chat turn, difference 3: NEITHER, EVER. Both the primer and the
163
207
  // attempts log exist to save a FRESH session from rediscovering what an
164
208
  // earlier one already learned; a chat turn is either the first message
@@ -171,13 +215,15 @@ function makePlanRun({ project, root, id, request, isChat, runnerApi, hostedEnv,
171
215
  const repoPrimer = formatRepoPrimer(repoMap, attemptsSection ? attemptsSection.length : 0);
172
216
  // chat turn, difference 1: NO IDEA PREAMBLE. The app composes the persona,
173
217
  // room context and message; instructions such as "call report before you
174
- // finish" do not belong in chat. Only the other-apps rule and, when
175
- // needed, the apps-off rule are added for Claude Code and Codex, so the reply can offer Manage agent.
218
+ // finish" do not belong in chat. Only the rules every run keeps are added
219
+ // (agents.mjs chatRulesFor): a refusal stops and asks, for every engine
220
+ // (#6995), and for Claude Code and Codex the other-apps rule and, when
221
+ // needed, the apps-off rule, so the reply can offer Manage agent.
176
222
  let text = request.planMode === "draft"
177
223
  ? `Investigate the request using read-only research, then return an actionable implementation plan in your final response. Structure the response as a report: keep resolved or contextual findings in their own sections; put actionable work under a \`## Implementation plan\` heading with one \`### Step N: ...\` or \`### Issue X: ...\` heading per top-level item; put numbered substeps under a \`**Steps:**\` label; and label checks and open decisions clearly. Do not implement anything, use tools to modify files, or ask for permission to implement. The human will edit and approve or reject your final plan on the board.\n\n${String(request.prompt)}`
178
- : `${isChat ? "" : preambleFor(agent, { ...(made.isolated ? {} : { workplace: IN_PLACE_WORKPLACE }), computerApps: request.computerApps === true })}${String(request.prompt)}`;
179
- if (isChat && request.planMode !== "draft" && ["claude", "codex"].includes(agent)) {
180
- text = `${otherAppsRule()}${request.computerApps === true ? "" : computerAppsOffRule()}${text}`;
224
+ : `${isChat ? "" : preambleFor(agent, { ...(made.isolated ? {} : { workplace: IN_PLACE_WORKPLACE }), computerApps, boardServerKey, readApps: request.readApps, readOnly: request.readOnly === true })}${String(request.prompt)}`;
225
+ if (isChat && request.planMode !== "draft") {
226
+ text = `${chatRulesFor(agent, { computerApps, boardServerKey })}${text}`;
181
227
  }
182
228
  if (request.planMode === "execute") text += `\n\nHUMAN-APPROVED IMPLEMENTATION PLAN\nFollow this exact plan, including the human's edits. Ask the human about any material scope change before implementing it.\n\n${request.approvedPlan}`;
183
229
  if (note) text = `${text}\n\n${note}`;
@@ -191,6 +237,8 @@ function makePlanRun({ project, root, id, request, isChat, runnerApi, hostedEnv,
191
237
  : [];
192
238
  const resolved = commandFor(agent, settings.env ?? process.env, {
193
239
  planMode: request.planMode,
240
+ // An ask that only reads apps (#8261): the read-only tool set.
241
+ readOnly: request.readOnly === true,
194
242
  model: request.model,
195
243
  effort: request.effort,
196
244
  claudeEfforts: Array.isArray(claudeEfforts) ? claudeEfforts : [],
@@ -207,9 +255,15 @@ function makePlanRun({ project, root, id, request, isChat, runnerApi, hostedEnv,
207
255
  sessionKey: session.key,
208
256
  boardId,
209
257
  // The person's own apps (#481): only an explicit true from the app,
210
- // which sends it when this person turned the switch on for this agent.
211
- computerApps: request.computerApps === true,
258
+ // which sends it when this person turned the switch on for this agent,
259
+ // and only when their list could be read (#7550).
260
+ computerApps,
261
+ boardServerKey,
262
+ appServers,
263
+ mcpConfigPath: appServers ? join(await makeTempDir(tempDirs), "mcp.json") : undefined,
212
264
  });
265
+ // Written before the spawn, readable by this user only.
266
+ if (resolved.mcpConfigFile) await writeFile(resolved.mcpConfigFile.path, resolved.mcpConfigFile.text, { mode: 0o600 });
213
267
  const chosen = settings.claudeBin !== undefined
214
268
  ? { ...resolved, bin: settings.claudeBin, args: request.planMode === "draft" ? resolved.args : settings.claudeArgs ?? resolved.args }
215
269
  // THE RESOLVED PATH, NOT THE BARE NAME: the check above already found
@@ -222,6 +276,14 @@ function makePlanRun({ project, root, id, request, isChat, runnerApi, hostedEnv,
222
276
  for (const what of chosen.ignored ?? []) log(`[${id}] ignoring ${what}`);
223
277
  // `brief` is what the person typed, on its own - the adapters echo it
224
278
  // into the transcript instead of the preamble-wrapped `prompt`.
225
- return { prompt: text, brief: String(request.prompt), chosen, args: chosen.args.map((a) => a.replaceAll("{prompt}", () => text)) };
279
+ return { prompt: text, brief: String(request.prompt), chosen, notices, args: chosen.args.map((a) => a.replaceAll("{prompt}", () => text)) };
226
280
  };
227
281
  }
282
+
283
+ /** A private folder (0700) for one launch's MCP config, recorded so the run
284
+ * removes it when it ends. */
285
+ async function makeTempDir(tempDirs) {
286
+ const dir = await mkdtemp(join(tmpdir(), "viewable-mcp-"));
287
+ tempDirs?.push(dir);
288
+ return dir;
289
+ }
@@ -45,12 +45,22 @@ export function samePath(a, b) {
45
45
  * may reuse one of ITS OWN trees only (round 3 item 67). */
46
46
  export async function activeWorktreeForPromptRows(root, projectId, promptNodeId, settings, log = () => {}) {
47
47
  const trees = [];
48
- if (!promptNodeId) return { locked: false, trees };
48
+ // The trees this prompt's runs LEFT NO WORK IN and the runner removed when
49
+ // they ended (`sidecar.worktreeRemoved`, the path, #8266), with the sessions that lived in
50
+ // each: a reply that continues one gets the tree made again at that path; a tree merged, thrown away or pruned is not here.
51
+ const removedTrees = [];
52
+ if (!promptNodeId) return { locked: false, trees, removedTrees };
49
53
  const runnerApi = settings.runnerApi ?? runnerApiModule;
50
54
  const listed = await runnerApi.runs({ projectIds: [projectId] }, { env: settings.env, fetchImpl: settings.fetchImpl });
51
55
  if (!listed.ok) throw new Error(`Cannot verify prompt ownership: ${listed.error}`);
52
56
  for (const run of listed.runs ?? []) {
53
57
  if (fromIdOf(run.request) !== promptNodeId) continue;
58
+ // The path itself, not this run's own: a follow-up that reused an earlier
59
+ // run's tree and left it unchanged removed THAT path.
60
+ const removedPath = run.sidecar?.worktreeRemoved;
61
+ if (typeof removedPath === "string" && removedPath !== "" && !(await exists(removedPath))) {
62
+ removedTrees.push({ path: removedPath, sessions: [run.sidecar.claudeSessionId, run.sidecar.codexThreadId].filter((v) => typeof v === "string" && v !== "") });
63
+ }
54
64
  const title = titleFor(run.request);
55
65
  const expectedPath = worktreePath(root, run.id, title);
56
66
  if (!(await exists(expectedPath))) continue;
@@ -86,9 +96,9 @@ export async function activeWorktreeForPromptRows(root, projectId, promptNodeId,
86
96
  const mainInBranch = await git(["merge-base", "--is-ancestor", mainBranch, branch], root);
87
97
  if (branchInMain.ok && !mainInBranch.ok) continue; // merged into the default branch
88
98
  log(`[lock] prompt ${promptNodeId} is held by worktree ${expectedPath} on branch ${branch}`);
89
- return { locked: true, worktreePath: expectedPath, branch, requestId: run.id, trees };
99
+ return { locked: true, worktreePath: expectedPath, branch, requestId: run.id, trees, removedTrees };
90
100
  }
91
- return { locked: false, trees };
101
+ return { locked: false, trees, removedTrees };
92
102
  }
93
103
 
94
104
  /** ROWS VERSION of the file-based `activeChatTurnForRoom` (`spawn.mjs`,
@@ -202,6 +212,11 @@ export async function admitRequest({ project, root, id, request, isChat, runnerA
202
212
  // checkRequest (pure) has said `cwd` and `roomId` are there. Each check
203
213
  // here refuses in words a person reads in the run's result, never throws.
204
214
  let chatCwd = null;
215
+ // True when the chat runs in the folder itself (a repo with no commit, or a
216
+ // later turn that hands the folder back): there is no copy of its own, so
217
+ // prepareRequestWorkspace holds it to the same "no second agent in one
218
+ // tree" gate a session gets.
219
+ let chatInFolder = false;
205
220
  if (isChat) {
206
221
  // WHERE IT RUNS: refused if it escapes the folder (Write, Edit and Bash).
207
222
  const resolvedCwd = resolveChatCwd(root, request.cwd);
@@ -216,6 +231,7 @@ export async function admitRequest({ project, root, id, request, isChat, runnerA
216
231
  // A BOARD'S SUBFOLDER (viewableFolder.mjs) is made inside the chat tree.
217
232
  const board = request.boardFolder === undefined ? null : chatBoardOf(root, resolvedCwd.path, request.boardFolder);
218
233
  chatCwd = board?.tree ?? resolvedCwd.path;
234
+ if (samePath(chatCwd, root)) chatInFolder = true;
219
235
  // THE DIRECTORY IS THE CONVERSATION (brief 25 difference 2): no worktree
220
236
  // PER MESSAGE and no fallback to the linked checkout. `mintIfMissing`
221
237
  // (ruling 1) cuts the folder's one long-lived chat worktree, once.
@@ -226,10 +242,13 @@ export async function admitRequest({ project, root, id, request, isChat, runnerA
226
242
  preparation.check();
227
243
  if (!minted.ok) {
228
244
  const detail = `NOTHING WAS SPAWNED AND NOTHING WAS BILLED.\n\n${minted.reason}`;
229
- log(`[${id}] refused: the chat worktree ${chatCwd} could not be made`);
245
+ log(`[${id}] refused: the chat copy ${chatCwd} could not be made`);
230
246
  return { patch: { status: "error", result: `ERROR\n\n${detail}\n`, finished_at: new Date().toISOString() } };
231
247
  }
232
248
  log(`[${id}] ${minted.detail}`);
249
+ // A folder with no commit has nothing to cut a copy from: the chat runs
250
+ // in the folder itself (and a board's subfolder is made there).
251
+ if (minted.folder === true) { chatCwd = minted.path; chatInFolder = true; }
233
252
  isDir = true;
234
253
  }
235
254
  if (!isDir) {
@@ -282,11 +301,17 @@ export async function admitRequest({ project, root, id, request, isChat, runnerA
282
301
  const from = isChat ? undefined : fromIdOf(request);
283
302
  // THE ONE TREE A REQUEST MAY NAME: one of this idea's own (round 3 item 67).
284
303
  let ownTreePath = null;
304
+ let ownTreeRemoved = null;
285
305
  if (from) {
286
306
  const lock = await activeWorktreeForPromptRows(root, project.id, from, settings, log);
287
307
  // The tree's own spelling goes down (round 4 item 70): reuseWorktree
288
308
  // compares text, and the request may say /var for a /private/var tree.
289
309
  ownTreePath = lock.trees.find((tree) => samePath(tree, request.worktreePath)) ?? null;
310
+ // The removed tree this request continues: the one it names, or (the
311
+ // resume op names none once the sidecar dropped the path) the one its
312
+ // session lived in.
313
+ const wantedSession = typeof request.resumeSessionId === "string" ? request.resumeSessionId.trim() : "";
314
+ ownTreeRemoved = lock.removedTrees.find((tree) => samePath(tree.path, request.worktreePath) || (wantedSession !== "" && tree.sessions.includes(wantedSession)))?.path ?? null;
290
315
  if (lock.locked) {
291
316
  // A resume, or a new session (Codex, opencode) naming the kept tree
292
317
  // (review 2026-10-04, D7): both run IN that tree, so neither is a second one.
@@ -335,5 +360,5 @@ export async function admitRequest({ project, root, id, request, isChat, runnerA
335
360
  resolvedBinPath = resolvedBin.path;
336
361
  }
337
362
 
338
- return { referenceImages, chatCwd, isResume, from, ownTreePath, agent, resolvedBinPath };
363
+ return { referenceImages, chatCwd, chatInFolder, isResume, from, ownTreePath, ownTreeRemoved, agent, resolvedBinPath };
339
364
  }
@@ -36,9 +36,16 @@ export function resumeNotes(request) {
36
36
  return { TREE_GONE_NOTE, NOT_FOUND_NOTE };
37
37
  }
38
38
 
39
- /** Spawn the run's process and see it through to its receipt. */
40
- export async function startRun(ctx, state, { timing, receipt, preparation, finish }) {
41
- const { root, id, request, isChat, runnerApi, rowsOpts, hostedEnv, session, boardId, settings, log } = ctx;
39
+ /** Spawn the run's process and see it through to its receipt. The folders the
40
+ * run's MCP config files were written in go whichever way it ends, a failure
41
+ * before the engine starts included (#7591: they were made in `planRun`, ahead
42
+ * of the first `try`). */
43
+ export async function startRun(ctx, state, options) {
44
+ try { return await runStarted(ctx, state, options); } finally { await removeTempDirs(state.tempDirs); }
45
+ }
46
+
47
+ async function runStarted(ctx, state, { timing, receipt, preparation, finish }) {
48
+ const { root, id, request, isChat, fromAutomation, runnerApi, rowsOpts, hostedEnv, session, boardId, settings, log } = ctx;
42
49
  const { referenceImages, from, agent, made, useStreaming, boardToken, childMcpUrl, hostedCallTool, isPersistent, maxMs, resumeTreeGone, resumeSessionId, planRun } = state;
43
50
  const { TREE_GONE_NOTE, NOT_FOUND_NOTE } = resumeNotes(request);
44
51
  const plan = await planRun({ resumeId: resumeSessionId, note: resumeTreeGone ? TREE_GONE_NOTE : null });
@@ -46,8 +53,14 @@ export async function startRun(ctx, state, { timing, receipt, preparation, finis
46
53
 
47
54
  let prepared = { wrote: null };
48
55
  try {
49
- prepared = await prepareWorkspace(agent, { mcpUrl: childMcpUrl, token: boardToken, sessionKey: session.key, boardId });
56
+ prepared = await prepareWorkspace(agent, { mcpUrl: childMcpUrl, token: boardToken, sessionKey: session.key, boardId, cwd: made.cwd, env: settings.env ?? process.env });
50
57
  } catch (error) {
58
+ // opencode with another board server it cannot switch off (#7550): the
59
+ // run does not start, and says what to do.
60
+ if (error?.refused) {
61
+ log(`[${id}] ${error.message}`);
62
+ return finish({ status: "error", result: `ERROR\n\n${error.message}\n`, finished_at: new Date().toISOString() });
63
+ }
51
64
  log(`[${id}] could not prepare the board config: ${error?.message ?? error}`);
52
65
  }
53
66
 
@@ -69,6 +82,8 @@ export async function startRun(ctx, state, { timing, receipt, preparation, finis
69
82
  const childEnvObj = childEnv(settings.baseEnv ?? process.env, { root, session, depth: settings.depth, fromId: from });
70
83
  if (boardToken) childEnvObj.PM_BOARD_TOKEN = boardToken;
71
84
  Object.assign(childEnvObj, prepared.env ?? {});
85
+ // Claude: claude.ai connectors off in every run (#7550, agents.mjs).
86
+ Object.assign(childEnvObj, chosen.env ?? {});
72
87
  // npm agents use /usr/bin/env node. Discovery alone is not enough after
73
88
  // nvm/fnm removes the old Node: every spawn and retry needs its new bin dir.
74
89
  const windows = (settings.platform ?? process.platform) === "win32";
@@ -96,9 +111,9 @@ export async function startRun(ctx, state, { timing, receipt, preparation, finis
96
111
  // (it stays read-only).
97
112
  const askPermission = boardToken && request.planMode !== "draft" && (useStreaming || agentFor(agent) === "codex" || chosen.spec?.protocol === "acp")
98
113
  ? createPermissionAsker({
99
- folder: root, cwd: made.cwd, agentLabel: AGENTS[agentFor(agent)]?.label ?? "The agent", session, boardId, fromId: from, env: hostedEnv,
114
+ folder: root, cwd: made.cwd, agentLabel: AGENTS[agentFor(agent)]?.label ?? "The agent", session, boardId, fromId: from, env: hostedEnv, automation: fromAutomation === true,
100
115
  callTool: hostedCallTool, poll: rowsPoll, log: (message) => log(`[${id}] ${message}`),
101
- pollMs: settings.permissionPollMs ?? 2000,
116
+ pollMs: settings.permissionPollMs ?? 2000, askTool: AGENTS[agentFor(agent)]?.boardTool("ask_user"),
102
117
  })
103
118
  : undefined;
104
119
 
@@ -190,6 +205,11 @@ export async function startRun(ctx, state, { timing, receipt, preparation, finis
190
205
  }
191
206
  }
192
207
 
208
+ /** The private folders the run's MCP config files were written in (#7550). */
209
+ async function removeTempDirs(dirs) {
210
+ for (const dir of dirs ?? []) await rm(dir, { recursive: true, force: true }).catch(() => {});
211
+ }
212
+
193
213
  /** The options one try of the engine runs with, for a plan from `planRun`.
194
214
  * `extra` overrides the defaults (a retry's shorter `maxMs`). */
195
215
  function runOptionsFor({ id, request, runnerApi, rowsOpts, settings, log }, { agent, made, useStreaming, maxMs }, { imageSuffix, onChunk, childEnvObj, stopCheck, answerPoll, askPermission, receipt }) {
@@ -235,7 +255,14 @@ function runOptionsFor({ id, request, runnerApi, rowsOpts, settings, log }, { ag
235
255
  ...(promptOnStdin ? { input: renderedPrompt } : {}),
236
256
  acp: p.chosen.acp ?? null,
237
257
  codex: p.chosen.codex ?? null,
258
+ // Where this run's board is, read the way the runner's own checks read
259
+ // it (claudeAppServers); the child's env is an allowlist without it (#7591).
260
+ boardEnv: settings.env ?? process.env,
238
261
  askPermission,
262
+ // The run's own board server, exempt from the other-board refusal, and
263
+ // what the runner tells the person before the agent starts (#7550).
264
+ boardServerKey: p.chosen.boardServerKey,
265
+ notices: p.notices ?? [],
239
266
  log: (message) => log(`[${id}] ${message}`),
240
267
  };
241
268
  return useStreaming
package/lib/runnerOps.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  import { serviceComputerApps, flushComputerApps } from "./computerApps.mjs";
8
8
  import { serviceFolderRead } from "./folderReads.mjs";
9
9
  import * as runnerApiModule from "./runnerApi.mjs";
10
- import { folderRestoreGeneration, removeFolder, withRegistryLock } from "./registry.mjs";
10
+ import { folderRestoreGeneration, removeFolderHoldingLock, withRegistryLock } from "./registry.mjs";
11
11
  import { deleteWorktree, mergeWorktree } from "./worktree.mjs";
12
12
  import { relaunchServer, readWorktreeRecord } from "./devserver.mjs";
13
13
 
@@ -66,7 +66,7 @@ export async function serviceForgetOps(root, project, ops, settings, log = () =>
66
66
  // The compare, local removal and acknowledgement share init's restore lock:
67
67
  // no restore can slip between this check and either destructive operation.
68
68
  if (await folderRestoreGeneration(root, env) !== generation) return false;
69
- const { removed } = await removeFolder(root, env);
69
+ const { removed } = await removeFolderHoldingLock(root, env);
70
70
  log(
71
71
  removed
72
72
  ? `forget: the board asked for ${root} to be removed - dropped it from the folder registry`
@@ -7,7 +7,7 @@ import { statSync } from "node:fs";
7
7
  import { basename } from "node:path";
8
8
 
9
9
  import * as runnerApiModule from "./runnerApi.mjs";
10
- import { addFolder, foldersWithoutGit, isScratchFolder, markFolderRestore, readRegistry, readRegistryChecked, withRegistryLock } from "./registry.mjs";
10
+ import { addFolderHoldingLock, foldersWithoutGit, isScratchFolder, markFolderRestore, readRegistry, readRegistryChecked, withRegistryLock, withoutRemoved } from "./registry.mjs";
11
11
  import { platformMark } from "./platform.mjs";
12
12
  import { SIGN_IN_AGENTS } from "./signIn.mjs";
13
13
 
@@ -60,7 +60,7 @@ export const presenceBody = (settings, { goodbye } = {}) => {
60
60
  * keeps the last good list. */
61
61
  export async function refreshProjectPaths(root, settings) {
62
62
  const { folders, ok } = await readRegistryChecked(settings.env ?? process.env);
63
- if (ok) settings.projectPaths = [...new Set([...folders, root])];
63
+ if (ok) settings.projectPaths = [...new Set([...await withoutRemoved(folders, settings.env ?? process.env), root])];
64
64
  }
65
65
 
66
66
  export async function registerAndFindProject(root, settings, { readd = false, onlyRoot = false } = {}) {
@@ -71,7 +71,7 @@ export async function registerAndFindProject(root, settings, { readd = false, on
71
71
  const out = await registerProject(root, settings, { readd: true });
72
72
  // Publish the local entry before releasing the restore lock. syncRegistry
73
73
  // in init remains idempotent, including when Remove won the lock first.
74
- if (out.ok) await addFolder(root, env);
74
+ if (out.ok) await addFolderHoldingLock(root, env);
75
75
  return out;
76
76
  }, env);
77
77
  }
@@ -81,7 +81,8 @@ export async function registerAndFindProject(root, settings, { readd = false, on
81
81
  async function registerProject(root, settings, { readd = false, onlyRoot = false } = {}) {
82
82
  const runnerApi = settings.runnerApi ?? runnerApiModule;
83
83
  const env = settings.env ?? process.env;
84
- const folders = await readRegistry(env);
84
+ // A removed folder is not advertised even when a stray write listed it (#8325).
85
+ const folders = await withoutRemoved(await readRegistry(env), env);
85
86
  // Init only owns this folder; a routine daemon register owns the full list.
86
87
  settings.projectPaths = [...new Set([...folders, root])];
87
88
  const paths = readd || onlyRoot ? [root] : folders.length > 0 ? folders : [root];